const { error } = require("console");
var express = require("express");
var router = express.Router();
const fs = require("fs");
const path = require("path");
const _ = require("lodash");

/* GET users listing. */
router.post("/", function (req, res, next) {
  const userid = req.body.userid;
  const filePath = req.body.filePath;
  const response = {
    message: "",
    success: true,
    file: "",
  };
  try {
    const allData = fs.readFileSync(
      path.resolve(__dirname, "../data/data.json"),
      "utf8"
    );
    const userData = JSON.parse(allData).users.find(
      (item) => item.userid === userid
    );
    if (userData) {
      console.log("🚀 ~ filePath:", filePath);
      if (fs.existsSync(filePath)) {
        const fileData = fs.readFileSync(filePath, { encoding: null });
        response.success = true;
        response.message = "请求成功";
        response.file = fileData;
        res.send(JSON.stringify(response));
      } else {
        response.success = false;
        response.message = "未找到文件";
        response.file = "";
        res.send(JSON.stringify(response));
      }
    } else {
      response.success = false;
      response.message = "用户不存在，请注册";
      res.send(JSON.stringify(response));
    }
  } catch (err) {
    console.error(`Got an error trying to read the file: ${err.message}`);
    res.send("error", error);
  }
});

module.exports = router;
